package com.cwk.yygh.hosp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cwk.yygh.common.exception.YyghException;
import com.cwk.yygh.common.result.ResultCodeEnum;
import com.cwk.yygh.common.utils.MD5;
import com.cwk.yygh.hosp.mapper.HospitalSetMapper;
import com.cwk.yygh.hosp.service.HospitalSetService;
import com.cwk.yygh.model.hosp.HospitalSet;
import com.cwk.yygh.vo.hosp.HospitalSetQueryVo;
import com.cwk.yygh.vo.order.SignInfoVo;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class HospitalSetServiceImpl extends ServiceImpl<HospitalSetMapper, HospitalSet> implements HospitalSetService {


    @Override
    public Page<HospitalSet> findPageHospitalSet(Long current, Long limit, HospitalSetQueryVo hospitalSetQueryVo) {
        Page<HospitalSet> page=new Page<>(current,limit);
        QueryWrapper<HospitalSet> wrapper = new QueryWrapper<>();
        wrapper.lambda().like(hospitalSetQueryVo.getHosname() != null&&!"".equals(hospitalSetQueryVo.getHoscode()), HospitalSet::getHosname, hospitalSetQueryVo.getHosname());
        wrapper.lambda().like(hospitalSetQueryVo.getHoscode() != null&&!"".equals(hospitalSetQueryVo.getHoscode()), HospitalSet::getHoscode, hospitalSetQueryVo.getHoscode());
        return page(page, wrapper);
    }

    @Override
    public boolean saveHospitalSet(HospitalSet hospitalSet) {
        hospitalSet.setStatus(1);
        Random random = new Random();
        hospitalSet.setSignKey(MD5.encrypt(System.currentTimeMillis()+""+random.nextInt(1000)));
        return save(hospitalSet);
    }

    @Override
    public void lockHospSet(Long id, Integer status) {
        HospitalSet hospitalSet = getById(id);
        hospitalSet.setStatus(status);
        updateById(hospitalSet);
    }

    @Override
    public String getSignKey(String hoscode) {
        QueryWrapper<HospitalSet> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(HospitalSet::getHoscode,hoscode);
        HospitalSet signKey = baseMapper.selectOne(queryWrapper);
        if(signKey == null)
            return null;
        return signKey.getSignKey();
    }

    @Override
    public SignInfoVo getSignInfoVo(String hoscode) {
        QueryWrapper<HospitalSet> wrapper = new QueryWrapper<>();
        wrapper.eq("hoscode",hoscode);
        HospitalSet hospitalSet = baseMapper.selectOne(wrapper);
        if(null == hospitalSet) {
            throw new YyghException(ResultCodeEnum.HOSPITAL_OPEN);
        }
        SignInfoVo signInfoVo = new SignInfoVo();
        signInfoVo.setApiUrl(hospitalSet.getApiUrl());
        signInfoVo.setSignKey(hospitalSet.getSignKey());
        return signInfoVo;
    }
}
